package mqq.controller;

import java.awt.Point;
import java.awt.event.MouseEvent;
import java.util.List;

import mqq.model.DecisionLinesEvent;
import mqq.model.Edge;
import mqq.view.Application;
import mqq.view.ApplicationPanel;

/**
 * Controller to manage the edge drawing
 * @author mqq
 */
public class DrawEdgeController {
	/** Boundary object responsible for */
	ApplicationPanel view;
	
	/** Entity object responsible for */
	DecisionLinesEvent event;
	
	/** React to changes by updating given entity. */
	public DrawEdgeController (DecisionLinesEvent e, ApplicationPanel app) {
		this.event = e;
		this.view = app;
	}
	
	/**
	 * React to the user's mouse event
	 * @param me  Mouse event taken
	 */
	public void mousePressed(MouseEvent me) {
		if (view.getDrawingActive()) {
			int numLines = event.getNumLines();
			if (this.pointInBound(me.getPoint())) {
				double width = 480 / (numLines - 1);
				int x = me.getPoint().x;
				int leftLine = 0;
				for (int i = 0; i < numLines - 1; i++) {
					if (x < 60 + width * (i + 1) && x > 60 + width * i) {
						leftLine = i;
					}
				}
				Edge newEdge = new Edge(leftLine, leftLine + 1, me.getPoint().y);
				if (event.addEdge(newEdge)) {
					view.getDrawingPanel().repaint();
					this.view.setWarning("");
					if (this.event.isDone()) {
						view.setDrawingActive(false);
						System.out.println("Here is the prioritized list:");
						String[] result = this.event.prioritizedChoices();
						for (int i = 0; i < this.event.getNumLines(); i++) {
							System.out.println(result[i]);
						}
					}
				} else {
					this.view.setWarning("Invalid edge: NonAdjacency constraint violated. Please try again.");
				}
			}
		}
	}
	
	/**
	 * Check if the point is in the drawing panel
	 * @param p  The given point
	 * @return  true if in; false if out
	 */
	private boolean pointInBound(Point p) {
		return p.x > 60 && p.x < 540 && p.y > 0 && p.y < 340;
	}
}
